﻿using Common.Infrastructure.Structs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Common.Infrastructure
{
    public static class LibSerialUtils
    {
        public static string GetSerial(IServiceProvider provider, string typeCode)
        {
            var s = GetSerials(provider, typeCode, 1);
            return s?.FirstOrDefault();
        }

        public static List<string> GetSerials(IServiceProvider provider, string typeCode, int count)
        {
            LibCheckNullUtils.CheckNull(typeCode, "typeCode");
            LibCheckNullUtils.CheckNull(count, "count");
            var req = new SerialRequest() { TypeCode = typeCode, Count = count };
            var config = GetConfiguration(provider);
            var serviceCode = config["SerialServiceCode"];
            if (string.IsNullOrEmpty(serviceCode))
            {
                serviceCode = "Base";
            }

            var ret = ServiceCallUtils.PostGetAsync<SerialResponse>(provider, serviceCode, "Serial/GetSerial", req).Result;
            return ret?.Serials;
        }

        private static IConfiguration GetConfiguration(IServiceProvider provider)
        {
            IConfiguration capPublisher = null;
            try
            {
                if (provider != null)
                {
                    capPublisher = provider.GetService<IConfiguration>();
                }
            }
            catch
            {
            }

            return capPublisher == null ? throw new CommonException("IConfiguration null") : capPublisher;
        }
    }
}
